<?php

namespace app\admin\controller\facrm\workweixin;

use app\admin\model\Admin;
use app\common\controller\Backend;
use EasyWeChat\Factory;

use  app\admin\model\facrm\qywx\User as QywxUser;

use  app\admin\model\facrm\qywx\Contacts as Qywxontacts;
use think\Db;


/**
 * 微信客户管理
 * @icon fa fa-circle-o
 */
class Contacts extends Backend
{

    protected $model = null;
    protected $distinguish = true;


    public function _initialize()
    {
        parent::_initialize();
        $this->request->filter(['strip_tags']);
        $this->model = (new Qywxontacts());

    }

    /**
     * 查看列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->field('weigh', true)
                ->with([
                    'customer' => function ($customer) {
                        $customer->with(['ownerUser' => function ($user) {
                            $user->field('id,username,nickname');
                        }])->field('id,name,owner_user_id');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 同步客户
     */
    public function syn($next_cursor="",$is_action=true,$page=1)
    {

        $syn_number=0;//同步数量
        //请提前同步好企业员工再同步客户
        set_time_limit(0);
        $key = "work_weixin_set";
        $settingModel = new \app\admin\model\facrm\Setting();
        $row = $settingModel->where('key', $key)->find();
        if (!$row) $this->error(__("企业微信未配置"));

        $values = json_decode($row['values'], true);//获取器不知道为什么失效了

        if (!$values) $this->error(__("企业微信未配置1"));

        $c_config = [
            'corp_id' => $values['corp_id'],
            'secret' => $values['customer_secret'], // 客户的 secret
        ];
        $appc = Factory::work($c_config);

        $qywxUserModel = new QywxUser();
        $userList = $qywxUserModel->page($page,100)->order('id asc')->column('admin_id','userid');
        if (!$userList){
            $this->success("同步完成");
        }

        $contactsModel = new \app\admin\model\facrm\qywx\Contacts();

        $externalcontact = new \addons\facrm\library\extend\easywechat\Externalcontact($appc);
        try {
            //批量查询客户详情
            $externalList = $externalcontact->batch(array_keys($userList),$next_cursor,100);
        } catch (\Exception $e) {

            $this->error($e->getMessage());
        }
        if (!$externalList || $externalList['errcode'] != '0' ){
            $this->error($externalList['errmsg']);
        }
        if ($externalList['external_contact_list']&&count($externalList['external_contact_list'])>0){
            $syn_number=count($externalList['external_contact_list']);
            foreach ($externalList['external_contact_list'] as $row) {
                $follow_user = $row['follow_info'];
                $admin_id=isset($userList[$follow_user['userid']])?$userList[$follow_user['userid']]:0;

                $contactsModel->getContacts($row, $values, ['admin_id' => $admin_id]);
            }
            if (isset($externalList['next_cursor'])&&$externalList['next_cursor']){
                $syn_number+=$this->syn($externalList['next_cursor'],false,$page);
            }

        }
        if (!$is_action){
            return $syn_number;
        }

        $this->success("本次同步更新{$syn_number}条数据",'',['page'=>$page,'count'=>count($userList)]);

    }


}
